package titt.io.reader;

import titt.error.TITTException;
import titt.head.Content;
import titt.head.ContentHead;
import titt.head.response.ResponseHead;
import titt.io.encoding.Decoder;
import titt.io.socket.TITTSocket;
import titt.type.Type;
import titt.type.TypedObject;

public class ResponseReader implements Reader<TypedObject> {

	private final TITTSocket s;
	private final Decoder denc;
	private final ResponseHead rh;
	private final Type rt;
	
	public ResponseReader(TITTSocket s, Decoder denc, ResponseHead rh) {
		this.s = s;
		this.denc = denc;
		this.rh = rh;
		this.rt = null;
	}
	
	public ResponseReader(TITTSocket s, Decoder denc, ResponseHead rh, Type returntype) {
		this.s = s;
		this.denc = denc;
		this.rh = rh;
		this.rt = returntype;
	}
	
	
	@Override
	public TypedObject[] readValues() throws Exception {
		TypedObject[] ret = new TypedObject[1];
		
		ContentHead c = new Content(rh);

		if(rh.getStatusCode() != 200 && !c.containsContentLength()) 
			throw new TITTException(rh.getStatusCode());

		byte[] complete = new byte[c.getContentLength()];
		
		s.getInputStream().read(complete);
		
		Type t = rt == null? new Type(rh.getContentType()) : rt;
		
		if(!denc.isDecodeable(t)) 
			ret[0] = new TypedObject(t,null);
		else
			ret[0] = new TypedObject(t, denc.decode(t, complete));

		if(rh.getStatusCode() != 200) throw new TITTException(rh.getStatusCode(), (String)ret[0].getObject());

		
		return ret;
	}

}
